/*
 * <h3>Title:wheel-parent系统</h3>
 * <p>Copyright (c) 2019, wnfbx@163.com. All rights reserved.</p>
 * @author wnfbx@163.com
 */
package com.wheel.autoconfigure.web.mvc.configvalidator;

import com.wheel.core.exception.ResultCode;
import com.wheel.core.utils.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;

import java.lang.reflect.Field;
import java.util.Locale;

/**
 * <dt>Description:ResultMessageCodeMessageValidator</dt>
 * <dd>验证系统默认异常code是否在i18n中定义了</dd>
 *
 * @author wnfbx@163.com
 * @version 1.0 <i>2019/12/25 15:08</i>
 * @since jdk1.7+
 */
public class ConfigurationValidator {

    private static final Logger log = LoggerFactory.getLogger(ConfigurationValidator.class);
    private MessageSource messageSource;

    public ConfigurationValidator(MessageSource messageSource) throws Exception {
        this.messageSource = messageSource;
        validateResultMessageCodeMessage();
    }

    /**
     * <dt>Description:validateResultMessageCodeMessage</dt>
     * <dd>验证通用返回消息列表</dd>
     * <dd>author: wnfbx@163.com</dd>
     * <dd>version:1.0 <i>2019/12/26 13:22</i></dd>
     *
     * @since jdk1.7+
     */
    private void validateResultMessageCodeMessage() throws Exception {
        StringBuilder result = new StringBuilder();
        Field[] declaredFields = ResultCode.class.getDeclaredFields();
        for (Field field : declaredFields) {
            if (field.getType().isAssignableFrom(String.class)) {
                field.setAccessible(true);
                String name = field.getName();
                if ("code".equals(name)) {
                    continue;
                }
                String key = (String) field.get(field);
                try {
                    String message = messageSource.getMessage(key, null, Locale.getDefault());
                    Log.trace(log, message);
                } catch (Exception e) {
                    result.append(key).append(" ");
                }
            }
        }
        if (result.length() > 0) {
            Log.error(log, result.toString());
            throw new Exception("系统未找到默认配置的消息内容，请确认配置了I18n，或者工程配置包涵spring.messages.basename=i18n/messages,i18n/validation,并且与工程配置位置不冲突");
        }
    }
}
